#ifndef DATA_TRANSMITTER_H
#define DATA_TRANSMITTER_H

#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266HTTPClient.h>
#include "ai_energy_analyzer.h" // 包含PowerData和EnergyInsight结构体定义

// 服务器配置
#define SERVER_HOST "your-server.com"
#define SERVER_PORT 80
#define DATA_ENDPOINT "/api/energy/data"
#define INSIGHT_ENDPOINT "/api/energy/insight"
#define STATUS_ENDPOINT "/api/energy/status"

// 重试配置
#define MAX_RETRY_COUNT 3
#define RETRY_DELAY_MS 1000

class DataTransmitter {
private:
  WiFiClient client;
  HTTPClient http;
  
  // 通信状态
  bool isConnected;
  unsigned long lastConnectionAttempt;
  unsigned long lastSuccessfulTransmission;
  
  // 错误统计
  int transmissionErrors;
  int reconnectionAttempts;
  
  // WiFi参数
  const char* ssid;
  const char* password;
  
  // 服务器参数
  String serverHost;
  int serverPort;
  String dataEndpoint;
  String insightEndpoint;
  String statusEndpoint;
  
  // 构建HTTP请求体
  String buildDataRequestBody(PowerData data);
  String buildInsightRequestBody(EnergyInsight insight);
  
  // 发送HTTP请求
  bool sendHttpRequest(String endpoint, String requestBody);
  
  // 检查WiFi连接
  bool checkWiFiConnection();
  
  // 尝试重新连接WiFi
  bool reconnectWiFi();
  
  // 获取连接状态信息
  String getConnectionStatus();
  
  // 记录通信错误
  void logCommunicationError(String error);
  
  // 格式化JSON数据
  String formatJSONValue(String key, String value, bool isString = true, bool last = false);
  String formatJSONValue(String key, float value, bool last = false);
  String formatJSONValue(String key, int value, bool last = false);
  String formatJSONValue(String key, bool value, bool last = false);
  
public:
  // 构造函数
  DataTransmitter();
  
  // 初始化数据传输器
  void init();
  
  // 发送电力数据
  bool sendData(PowerData data);
  
  // 发送能源洞察
  bool sendInsight(EnergyInsight insight);
  
  // 发送系统状态
  bool sendStatus(bool isOnline, String statusMessage);
  
  // 检查连接状态
  bool isServerConnected();
  
  // 获取WiFi信号强度
  int getWiFiSignalStrength();
  
  // 设置服务器参数
  void setServerParameters(String host, int port, String dataEP, String insightEP, String statusEP);
  
  // 设置WiFi参数
  void setWiFiParameters(const char* newSSID, const char* newPassword);
  
  // 获取统计信息
  int getTransmissionErrors();
  int getReconnectionAttempts();
  
  // 重置统计信息
  void resetStatistics();
};

// 构造函数
DataTransmitter::DataTransmitter() {
  isConnected = false;
  lastConnectionAttempt = 0;
  lastSuccessfulTransmission = 0;
  transmissionErrors = 0;
  reconnectionAttempts = 0;
  
  // 使用默认服务器参数
  serverHost = SERVER_HOST;
  serverPort = SERVER_PORT;
  dataEndpoint = DATA_ENDPOINT;
  insightEndpoint = INSIGHT_ENDPOINT;
  statusEndpoint = STATUS_ENDPOINT;
  
  // WiFi参数将在init()中设置
  ssid = nullptr;
  password = nullptr;
}

// 初始化数据传输器
void DataTransmitter::init() {
  // 在实际应用中，WiFi参数应该从配置中读取
  // 这里使用默认参数作为示例
  Serial.println("数据传输器已初始化");
}

// 构建HTTP请求体
String DataTransmitter::buildDataRequestBody(PowerData data) {
  String requestBody = "{";
  requestBody += formatJSONValue("timestamp", (unsigned long)data.timestamp, false);
  requestBody += formatJSONValue("voltage", data.voltage, false);
  requestBody += formatJSONValue("current", data.current, false);
  requestBody += formatJSONValue("power", data.power, false);
  requestBody += formatJSONValue("energy", data.energy, true);
  requestBody += "}";
  return requestBody;
}

// 构建能源洞察请求体
String DataTransmitter::buildInsightRequestBody(EnergyInsight insight) {
  String requestBody = "{";
  requestBody += formatJSONValue("hasAnomaly", insight.hasAnomaly, false);
  requestBody += formatJSONValue("anomalyType", insight.anomalyType, false);
  requestBody += formatJSONValue("hasRecommendation", insight.hasRecommendation, false);
  requestBody += formatJSONValue("recommendationType", insight.recommendationType, false);
  requestBody += formatJSONValue("recommendationText", insight.recommendationText, false);
  requestBody += formatJSONValue("autoOptimize", insight.autoOptimize, false);
  requestBody += formatJSONValue("estimatedSavings", insight.estimatedSavings, true);
  requestBody += "}";
  return requestBody;
}

// 发送HTTP请求
bool DataTransmitter::sendHttpRequest(String endpoint, String requestBody) {
  if (!checkWiFiConnection()) {
    return false;
  }
  
  // 构建完整的服务器URL
  String serverURL = "http://" + serverHost;
  if (serverPort != 80) {
    serverURL += ":" + String(serverPort);
  }
  serverURL += endpoint;
  
  // 开始HTTP请求
  http.begin(client, serverURL);
  http.addHeader("Content-Type", "application/json");
  
  // 发送POST请求
  int httpResponseCode = http.POST(requestBody);
  
  // 检查响应
  bool success = false;
  if (httpResponseCode > 0) {
    String response = http.getString();
    Serial.print("HTTP响应代码: ");
    Serial.println(httpResponseCode);
    Serial.print("响应内容: ");
    Serial.println(response);
    
    // 检查响应代码
    if (httpResponseCode >= 200 && httpResponseCode < 300) {
      success = true;
      lastSuccessfulTransmission = millis();
    }
  } else {
    Serial.print("HTTP请求失败，错误代码: ");
    Serial.println(httpResponseCode);
    transmissionErrors++;
  }
  
  // 结束HTTP请求
  http.end();
  
  return success;
}

// 检查WiFi连接
bool DataTransmitter::checkWiFiConnection() {
  if (WiFi.status() != WL_CONNECTED) {
    Serial.println("WiFi未连接");
    isConnected = false;
    return reconnectWiFi();
  }
  
  isConnected = true;
  return true;
}

// 尝试重新连接WiFi
bool DataTransmitter::reconnectWiFi() {
  // 检查是否已经在尝试重连
  unsigned long currentMillis = millis();
  if (currentMillis - lastConnectionAttempt < RETRY_DELAY_MS * 2) {
    return false;
  }
  
  lastConnectionAttempt = currentMillis;
  reconnectionAttempts++;
  
  Serial.print("尝试重新连接WiFi (" + String(reconnectionAttempts) + ")...");
  
  // 尝试重连
  int attempts = 0;
  while (WiFi.status() != WL_CONNECTED && attempts < MAX_RETRY_COUNT) {
    delay(1000);
    attempts++;
  }
  
  if (WiFi.status() == WL_CONNECTED) {
    Serial.println("已连接");
    Serial.print("IP地址: ");
    Serial.println(WiFi.localIP());
    isConnected = true;
    return true;
  } else {
    Serial.println("连接失败");
    return false;
  }
}

// 获取连接状态信息
String DataTransmitter::getConnectionStatus() {
  String status = "连接状态: ";
  
  if (isConnected) {
    status += "已连接";
    status += ", WiFi信号强度: " + String(getWiFiSignalStrength()) + " dBm";
    status += ", IP地址: " + WiFi.localIP().toString();
  } else {
    status += "未连接";
  }
  
  status += ", 传输错误: " + String(transmissionErrors);
  status += ", 重连尝试: " + String(reconnectionAttempts);
  
  return status;
}

// 记录通信错误
void DataTransmitter::logCommunicationError(String error) {
  Serial.print("通信错误: ");
  Serial.println(error);
  transmissionErrors++;
}

// 格式化JSON值 - 字符串类型
String DataTransmitter::formatJSONValue(String key, String value, bool isString, bool last) {
  String result = "\"" + key + "\":";
  
  if (isString) {
    // 处理字符串值，需要转义引号
    String escapedValue = value;
    escapedValue.replace("\"", "\\\"");
    result += "\"" + escapedValue + "\"";
  } else {
    result += value;
  }
  
  if (!last) {
    result += ",";
  }
  
  return result;
}

// 格式化JSON值 - 浮点类型
String DataTransmitter::formatJSONValue(String key, float value, bool last) {
  return formatJSONValue(key, String(value), false, last);
}

// 格式化JSON值 - 整数类型
String DataTransmitter::formatJSONValue(String key, int value, bool last) {
  return formatJSONValue(key, String(value), false, last);
}

// 格式化JSON值 - 布尔类型
String DataTransmitter::formatJSONValue(String key, bool value, bool last) {
  return formatJSONValue(key, value ? "true" : "false", false, last);
}

// 发送电力数据
bool DataTransmitter::sendData(PowerData data) {
  String requestBody = buildDataRequestBody(data);
  Serial.print("发送电力数据: ");
  Serial.println(requestBody);
  
  // 尝试发送数据，如果失败则重试
  for (int attempt = 0; attempt < MAX_RETRY_COUNT; attempt++) {
    if (sendHttpRequest(dataEndpoint, requestBody)) {
      return true;
    }
    
    if (attempt < MAX_RETRY_COUNT - 1) {
      Serial.println("发送失败，尝试重试...");
      delay(RETRY_DELAY_MS);
    }
  }
  
  logCommunicationError("发送电力数据失败");
  return false;
}

// 发送能源洞察
bool DataTransmitter::sendInsight(EnergyInsight insight) {
  String requestBody = buildInsightRequestBody(insight);
  Serial.print("发送能源洞察: ");
  Serial.println(requestBody);
  
  // 尝试发送数据，如果失败则重试
  for (int attempt = 0; attempt < MAX_RETRY_COUNT; attempt++) {
    if (sendHttpRequest(insightEndpoint, requestBody)) {
      return true;
    }
    
    if (attempt < MAX_RETRY_COUNT - 1) {
      Serial.println("发送失败，尝试重试...");
      delay(RETRY_DELAY_MS);
    }
  }
  
  logCommunicationError("发送能源洞察失败");
  return false;
}

// 发送系统状态
bool DataTransmitter::sendStatus(bool isOnline, String statusMessage) {
  String requestBody = "{";
  requestBody += formatJSONValue("isOnline", isOnline, false);
  requestBody += formatJSONValue("statusMessage", statusMessage, true);
  requestBody += "}";
  
  Serial.print("发送系统状态: ");
  Serial.println(requestBody);
  
  return sendHttpRequest(statusEndpoint, requestBody);
}

// 检查连接状态
bool DataTransmitter::isServerConnected() {
  return isConnected;
}

// 获取WiFi信号强度
int DataTransmitter::getWiFiSignalStrength() {
  return WiFi.RSSI();
}

// 设置服务器参数
void DataTransmitter::setServerParameters(String host, int port, String dataEP, String insightEP, String statusEP) {
  serverHost = host;
  serverPort = port;
  dataEndpoint = dataEP;
  insightEndpoint = insightEP;
  statusEndpoint = statusEP;
  
  Serial.print("服务器参数已更新: ");
  Serial.println(serverHost + ":" + serverPort);
}

// 设置WiFi参数
void DataTransmitter::setWiFiParameters(const char* newSSID, const char* newPassword) {
  ssid = newSSID;
  password = newPassword;
  
  Serial.print("WiFi参数已更新: ");
  Serial.println(ssid);
  
  // 如果已经连接，尝试使用新参数重新连接
  if (WiFi.status() == WL_CONNECTED) {
    WiFi.disconnect();
    delay(1000);
    reconnectWiFi();
  }
}

// 获取统计信息
int DataTransmitter::getTransmissionErrors() {
  return transmissionErrors;
}

int DataTransmitter::getReconnectionAttempts() {
  return reconnectionAttempts;
}

// 重置统计信息
void DataTransmitter::resetStatistics() {
  transmissionErrors = 0;
  reconnectionAttempts = 0;
  Serial.println("数据传输器统计信息已重置");
}

#endif // DATA_TRANSMITTER_H